package com.gitee.cui.server.handler;

import com.gitee.cui.common.cocurrent.FutureTaskScheduler;
import com.gitee.cui.common.common.bean.msg.ProtoMsg;
import com.gitee.cui.server.processor.ChatRedirectProcessor;
import com.gitee.cui.server.server.ServerSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/28 9:41
 **/
@Slf4j
@ChannelHandler.Sharable
@Service
public class ChatRedirectHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private ChatRedirectProcessor chatRedirectProcessor;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType type = message.getType();
        if (chatRedirectProcessor.type() != type) {
            super.channelRead(ctx, msg);
            return;
        }

        ServerSession session = ctx.channel().attr(ServerSession.SESSION_KEY).get();
        if (session == null || !session.isLogin()) {
            log.error("用户尚未登录，不能发送消息");
            return;
        }

        FutureTaskScheduler.add(() -> {
            chatRedirectProcessor.action(session, message);
        });
    }
}
